<template>
  <el-dialog v-model="visible" title="修改余额">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="用户名" prop="uname">
        <el-input v-model="dataForm.uname" disabled></el-input>
      </el-form-item>
      <el-form-item label="操作类型" prop="balanceType">
        <el-radio-group v-model="dataForm.balanceType">
          <el-radio :label="1">增加</el-radio>
          <el-radio :label="2">减少</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input-number v-model="dataForm.amount" controls-position="right" placeholder="金额" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" type="textarea" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  uname: "",
  balanceType: 1,
  amount: "",
  remark: ""
});

const rules = ref({
  amount: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  remark: [{ required: true, message: t("validate.required"), trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/member/member/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    dataForm.amount = "";
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    let { id, balanceType, amount, remark } = dataForm;
    let formData = {
      memberId: id,
      balanceType,
      amount,
      remark
    };
    baseService.put(`/member/member/balance/`, formData).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
